package crm8000.Controllers

import crm8000.services.PermissionService;
import crm8000.services.UserService;
import crm8000.services.WsBillService
import grails.converters.JSON

class SaleController {

	static allowedMethods = [wsbillList: 'POST', wsBillInfo: 'POST',
		editWSBill: 'POST', deleteWSBill: 'POST', wsBillDetailList: 'POST',
		editWSBillDetail: 'POST', refreshWSBillInfo: 'POST', wsBillDetailInfo: 'POST',
		deleteWSBillDetail: 'POST', commitWSBill: 'POST']

	PermissionService permissionService

	UserService userService

	WsBillService wsBillService

	def wsIndex() {
		if (!permissionService.hasPermission("2002")) {
			redirect controller: "home"
		}

		[loginUserName: userService.loginUserName]
	}

	def wsbillList() {
		def data = wsBillService.wsbillList()

		render data as JSON
	}

	def wsBillInfo() {
		def user = userService.loginUser
		def bill = wsBillService.wsBillInfo(params.id)

		render(contentType: "application/json") {
			ref = bill?.ref
			customerId = bill?.customer?.id
			customerName = bill?.customer?.name
			warehouseId = bill?.warehouse?.id
			warehouseName = bill?.warehouse?.name
			bizUserId = user.id
			bizUserName = user.name
		}
	}

	def editWSBill() {
		def result = wsBillService.editWSBill(params)

		render result as JSON
	}

	def deleteWSBill() {
		def result = wsBillService.deleteWSBill(params.id)

		render result as JSON
	}

	def wsBillDetailList() {
		def data = wsBillService.wsBillDetailList(params.billId)

		render(contentType: "application/json") {
			array {
				for (g in data) {
					goods id: g.id, goodsCode: g.goods.code, goodsName: g.goods.name,
					goodsSpec: g.goods.spec, unitName: g.goods.unit.name, goodsCount: g.goodsCount,
					goodsPrice: g.goodsPrice, goodsMoney: g.goodsMoney
				}
			}
		}
	}
	
	def editWSBillDetail() {
		def result = wsBillService.editWSBillDetail(params)
		
		render result as JSON	
	}
	
	def refreshWSBillInfo() {
		def data = wsBillService.refreshWSBillInfo(params.id)
		render(contentType: "application/json") {
			amount = data
		}
	}
	
	def wsBillDetailInfo() {
		def data = wsBillService.wsBillDetailInfo(params.id)
		
		render(contentType: "application/json") {
			goodsId = data.goods.id
			goodsCode = data.goods.code
			goodsName = data.goods.name
			goodsSpec = data.goods.spec
			goodsUnit = data.goods.unit.name
			goodsCount = data.goodsCount
			goodsPrice = data.goodsPrice
		}
	}
	
	def deleteWSBillDetail() {
		def result = wsBillService.deleteWSBillDetail(params.id)
		
		render result as JSON
	}
	
	def commitWSBill() {
		def result = wsBillService.commitWSBill(params.id)
		
		render result as JSON
	}

	/**
	 * 销售退货入库
	 * @return
	 */
	def srIndex() {
		if (!permissionService.hasPermission("2006")) {
			redirect controller: "home"
		}

		[loginUserName: userService.loginUserName]
	}

}
